from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import request
from flask import session

from info import constants, db
from info.models import News, User, Comment, CommentLike #, Collection
from info.modules.news import news_blue
from flask import render_template

from info.utils.common import user_login_data
from info.utils.response_code import RET


@news_blue.route("/news_comment", methods=["POST"])
@user_login_data
def news_comment():
    user = g.user
    if not user:
        return jsonify(errno=RET.PARAMERR, errmsg='用户未登录')
    
    params = request.json
    news_id = params.get("news_id", None)
    comment_str = params.get("comment", None)
    parent_id = params.get("parent_id", None)
    
    if not all([news_id, comment_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    news: News = None
    
    try:
        news = News.query.filter(News.id == news_id).first()
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, ermsg="参数错误")
    
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="参数错误")
    
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    if parent_id:
        comment.parent_id = parent_id
    comment.content = comment_str
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存失败")
    return jsonify(errno=RET.OK, errmsg="操做成功", data=comment.to_dict())


@news_blue.route('/news_collect', methods=["POST"])
@user_login_data
def collect_news():
    user = g.user
    if not user:
        return jsonify(errno=RET.SERVERERR, errmsg='用户未登录')
    
    news_id = request.json.get("news_id", None)
    action = request.json.get("action", None)
    
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    
    news = None
    
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    
    if action == "cancel_collect":
        if news in user.collection_news.all():
            
            user.collection_news.remove(news)
    else:
        if news not in user.collection_news.all():
            
            user.collection_news.append(news)
    try:
        db.session.commit()
    except:
        db.session.rollback()
        
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blue.route("/<int:news_id>")
@user_login_data
def new_detail(news_id: int):
    user = g.user
    news_list = []
    try:
        news_list = News.query.filter(News.status==0).order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)
    
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    
    news: News = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    
    if not news:
        abort(404)
    
    news.clicks += 1
    
    is_follow = False
    
    
    is_collected = False
    try:
        if user:
            if news in user.collection_news.all():
                is_collected = True
            
        db.session.commit()
    except:
        db.session.rollback()

    if news.user and user:
        if news.user in user.followers:
            is_follow = True
    
    comments = None
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
    
    comment_like_ids = []
    if g.user:
        
        try:
            comment_ids = [comment.id for comment in comments]
            if len(comment_ids) > 0:
                comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                                         CommentLike.user_id == g.user.id).all()
                comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.error(e)
    
    comment_dict_li = []
    for comment in comments:
        dict = comment.to_dict()
        dict['is_like'] = False
        if g.user and comment.id in comment_like_ids:
            dict["is_like"] = True
        comment_dict_li.append(dict)
    
    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "news": news.to_dict(),
        "is_collected": is_collected,
        "comments": comment_dict_li,
        "is_follow":is_follow
    }
    
    return render_template('news/detail.html', data=data)


@news_blue.route('/comment_like', methods=["POST"])
@user_login_data
def set_comment_like():

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    
  
    comment_id = request.json.get("comment_id")
    # news_id = request.json.get("news_id",None)
    action = request.json.get("action")
    
    # 判断参数
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    if action not in ("add", "remove"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    # 查询评论数据
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")
    
    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论数据不存在")
    
    if action == "add":
        comment_like = CommentLike()
        comment_like.comment_id = comment_id
        comment_like.user_id = user.id
        # comment_like.news_id = news_id
        db.session.add(comment_like)
        
        comment.like_count += 1
    else:
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -= 1
    
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")

@news_blue.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    user = g.user
    if not user:
        return jsonify(errno=RET.SERVERERR,errmsg="用户未登录")

    user_id = request.json.get("user_id")
    action = request.json.get("action")
    
    if not all([user_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")
    
    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查询到用户数据")
    
    if action == "follow":
        if target_user.followers.filter(User.id == user.id).count()>0:
            return jsonify(errno=RET.DBERR, errmsg="已经关注")
        target_user.followers.append(user)
    elif action == 'unfollow':
        if target_user.followers.filter(User.id == user.id).count() < 0:
            return jsonify(errno=RET.DBERR, errmsg="还未关注")
        target_user.followers.remove(user)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    return jsonify(errno=RET.OK, errmsg="操作成功")
    
    